<?php

declare(strict_types=1);

namespace app\admin\service;

use app\admin\model\Images;
use app\admin\model\MarketSmCopywriting as MarketSmCopywritingModel;
use app\admin\model\MarketSmCopywritingTasks as MarketSmCopywritingTasksModel;
use app\admin\model\MarketSocialMediaAccount as MarketSocialMediaAccountModel;
use app\admin\model\CryptoNews as CryptoNewsModel;
use app\admin\model\Images as ImagesModel;
use app\common\RabbitMQClient;
use think\facade\Db;

class MarketSmCopywritingTasks extends BaseService
{
    /**
     * 注册服务
     *
     * @return mixed
     */
    public function register()
    {
        //
    }

    /**
     * 执行服务
     *
     * @return mixed
     */
    public function boot()
    {
        //
    }

    /**
     * 批量生成社媒文案任务
     * @param $param
     * @return array|void
     */
    public function batchGeneration($param)
    {
        Db::startTrans();
        try {
            // 去掉限制，前端提示
            // $oCryptoNewsModel = Db::table('db_market_news_search_det')->where('crypto_news_id', $param['crypto_news_id'])->find();
            // if (!$oCryptoNewsModel) {
            //     return ['code' => 1, 'message' => '未匹配到搜索结果，请稍后重试或联系管理员！'];
            // }

            $oMarketSmCopywritingTasksModel = new MarketSmCopywritingTasksModel();
            $oMarketSmCopywritingTasksModel->crypto_news_id = $param['crypto_news_id'];
            $oMarketSmCopywritingTasksModel->channel_id = $param['channel_id'];
            $oMarketSmCopywritingTasksModel->language_id = $param['language_id'];
            $oMarketSmCopywritingTasksModel->account_group_id = $param['account_group_id'];
            $oMarketSmCopywritingTasksModel->mining_machine = $param['mining_machine'];
            $oMarketSmCopywritingTasksModel->cue_word = $param['cue_word'];
            $oMarketSmCopywritingTasksModel->imgs = implode(',', $param['imgs']);
            $oMarketSmCopywritingTasksModel->creator = $param['operator_id'];
            $oMarketSmCopywritingTasksModel->create_time = date('Y-m-d H:i:s');
            if (!$oMarketSmCopywritingTasksModel->save()) {
                throw new \Exception('添加任务失败！');
            }
            // 找到所有账号
            $oMarketSocialMediaAccountModel = MarketSocialMediaAccountModel::where([
                ['channel_id', '=', $param['channel_id']],
                ['language', '=', $param['language_id']],
                ['account_group_id', '=', $param['account_group_id']],
                ['status', '=', 1]
            ])->select();
            if(count($oMarketSocialMediaAccountModel) == 0){
                throw new \Exception('未找到可用账号！');
            }
            foreach ($oMarketSocialMediaAccountModel as $item) {
                $oMarketSmCopywritingModel = new MarketSmCopywritingModel();
                $oMarketSmCopywritingModel->sm_generate_opywriting_tasks_id = $oMarketSmCopywritingTasksModel->id;
                $oMarketSmCopywritingModel->social_media_account_id = $item->id;
                $oMarketSmCopywritingModel->cue_word = $param['cue_word'];
                $oMarketSmCopywritingModel->creator = $param['operator_id'];
                $oMarketSmCopywritingModel->create_time = date('Y-m-d H:i:s');
                if (!$oMarketSmCopywritingModel->save()) {
                    throw new \Exception('添加文案失败！');
                }
                $insertData = [
                    'id' => $oMarketSmCopywritingModel->id
                ];
                // 压入队列
                $rabbitMQService = new RabbitMQClient();
                $rabbitMQService->sendMessage('createCopywriting', json_encode($insertData));
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => 1, 'message' => $e->getMessage()];
        }
        $this->logger->logOperation(array_values($insertData),'MarketSmCopywritingTasks','批量生成','批量生成社媒文案任务队列执行');
        return ['code' => 0, 'message' => '操作成功！'];
    }

    /**
     * 读取任务信息
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read($param)
    {
        $where = [['id', '=', $param['id']]];
        $field = ['id', 'channel_id', 'language_id', 'account_group_id', 'mining_machine', 'cue_word', 'create_time', 'crypto_news_id', 'imgs'];
        $oMarketSmCopywritingTasksModel = MarketSmCopywritingTasksModel::with(['crypto_news', 'sm_copywriting'])->where($where)->field($field)->find();

        if ($oMarketSmCopywritingTasksModel->imgs) {
            $img_arr = explode(',', $oMarketSmCopywritingTasksModel->imgs);
            $oImages = new ImagesModel();
            $oMarketSmCopywritingTasksModel->imgs = $oImages->getImagesByIds($img_arr);
        } else {
            $oMarketSmCopywritingTasksModel->imgs = [];
        }
        foreach ($oMarketSmCopywritingTasksModel->sm_copywriting as &$item) {
            $item->social_media_account_id = $item->account_name ?? '';
            $item->creator = $item->creator_value ?? '';
            unset($item->creator_value);
            unset($item->account_name);
        }
        if (!$oMarketSmCopywritingTasksModel) {
            return ['code' => 1, 'message' => '获取信息失败！'];
        }
        return ['code' => 0, 'message' => 'success', 'data' => $oMarketSmCopywritingTasksModel];
    }
}
